import { defineStore } from 'pinia'
import { ref } from 'vue'

import { login, logout, getInfo } from '@/apis/login'
import { getToken, setToken, removeToken } from '@/utils/auth'

export const useUserStore = defineStore('user', () => {
  // 1. 定义管理用户数据的 state
  const userState = ref({
    token: getToken(),
    id: '',
    name: '',
    avatar: '',
    roles: [],
    permissions: []
  })

  // 2. 定义获取接口数据的 action 函数
  const actions = {
    // 登录
    async login(userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
   
      try {
        const res = await login(username, password, code, uuid)
        setToken(res.token)
        userState.value.token = res.token
     
        return res.data
      } catch (error) {
        throw error
      }
     
    },

    // 获取用户信息
    async getInfo() {
      try {
        const res = await getInfo()
        const user = res.user
        const avatar = (user.avatar === "" || user.avatar == null) ? require("@/assets/images/profile.jpg") : process.env.VUE_APP_BASE_API + user.avatar;
        if (res.roles && res.roles.length > 0) { // 验证返回的 roles 是否是一个非空数组
          userState.value.roles = res.roles
          userState.value.permissions = res.permissions
        } else {
          userState.value.roles = ['ROLE_DEFAULT']
        }
        userState.value.id = user.userId
        userState.value.name = user.userName
        userState.value.avatar = avatar
        return res
      } catch (error) {
        throw error
      }
    },

    // 退出系统
    async logOut() {
      try {
        await logout(userState.value.token)
        userState.value.token = ''
        userState.value.roles = []
        userState.value.permissions = []
        removeToken()
      } catch (error) {
        throw error
      }
    },

    // 前端登出
    fedLogOut() {
      userState.value.token = ''
      removeToken()
    }
  }

  // 3. 以对象的格式把 state 和 action 返回出去
  return { ...userState, ...actions }
})
